<template>
  <ContentWrap class="chem-record-wrap">
    <!-- 标题和添加一行按钮 -->
    <div class="chem-header">
      <div class="chem-title">有机化学品原料/粉尘取样记录表</div>
    </div>
    <!-- 头部信息表单 -->
    <el-form :model="form" class="chem-form" label-position="left"  >
      <el-row :gutter="30">
        <el-col :span="4">
          <el-form-item label="取样日期">
            <el-date-picker
              v-model="form.sampleDate"
              placeholder="选择日期"
              type="date"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="检测类别">
            <el-input v-model="form.type" placeholder="请输入" />
          </el-form-item>
        </el-col>

        <el-col :span="5">
          <el-form-item label="检测项目">
            <el-input v-model="form.item" placeholder="检测项目" readonly />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="采样依据">
            <el-select v-model="form.basis" disabled placeholder="请选择">
              <el-option
                label="顶空气相色谱-质谱法 GDOHTQC 001—2020"
                value="《化学品中挥发性有机组分定性分析和峰面积百分比测定顶空气相色谱-质谱法》GDOHTQC 001—2020"
              />
              <el-option
                label="游离二氧化硅含量 GBZ/T 192.4-2007"
                value="《工作场所空气中粉尘测定第4部分：游离二氧化硅含量》GBZ/T 192.4-2007"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <!-- 表格 -->
    <el-table :data="form.table" border class="chem-table" stripe>
      <el-table-column align="center" label="样品编号" prop="sampleNo" width="180">
        <template #default="{ row }">
          <el-input v-model="row.sampleNo" placeholder="" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="化学品原料/粉尘名称" prop="materialName" width="160">
        <template #default="{ row }">
          <el-input v-model="row.materialName" placeholder="" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="型号" prop="model" width="80">
        <template #default="{ row }">
          <el-input v-model="row.model" placeholder="" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="样品批号" prop="batch" width="100">
        <template #default="{ row }">
          <el-input v-model="row.batch" placeholder="" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="生产厂家" prop="manufacturer" width="100">
        <template #default="{ row }">
          <el-input v-model="row.manufacturer" placeholder="" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="样品性状" prop="physicalState" width="80">
        <template #default="{ row }">
          <el-input v-model="row.physicalState" placeholder="" @input="() => handlePhysicalStateChange(row)" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="样品颜色" prop="color" width="100">
        <template #default="{ row }">
          <el-input v-model="row.color" placeholder="" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="取样场所、岗位、地点" width="250" prop="place">
        <template #default="{ row }">
          <el-select v-model="row.place" placeholder="请选择" @visible-change="handleVisibleChange">
            <el-option v-for="item in placeOptions" :key="item" :label="item" :value="item" />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column align="center" label="代表/取样场所、岗位、地点"  prop="post">
        <template #default="{ row }">
          <el-select
            v-model="row.post"
            multiple
            filterable
            collapse-tags-tooltip
            placeholder="请选择"
            @visible-change="handlePostVisibleChange"
          >
            <el-option v-for="item in postOptions" :key="item" :label="item" :value="item" />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column align="center" label="取样量" prop="amount" width="80">
        <template #default="{ row }">
          <el-input v-model="row.amount" placeholder="" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="单位" prop="unit" width="100">
        <template #default="{ row }">
          <el-select v-model="row.unit" placeholder="请选择" @change="() => handleUnitChange(row)">
            <el-option label="ml" value="ml" />
            <el-option label="g" value="g" />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column align="center" label="工艺气温(℃)" width="80" prop="temperature">
        <template #default="{ row }">
          <el-input v-model="row.temperature" placeholder="" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="70" >
        <template #default="{ $index }">
          <el-button link type="danger" @click="removeRow($index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </ContentWrap>
</template>

<script lang="ts" setup>
import { onMounted, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import ContentWrap from '@/components/ContentWrap/src/ContentWrap.vue'
import { ProjectApi } from '@/api/dk/project'
import { useRoute, useRouter } from 'vue-router'

// 定义 props 来接收 test-item 属性
const props = defineProps<{
  testItem?: string
}>()

const emit = defineEmits(['change'])

const route = useRoute()
const router = useRouter()

// 修改 form 的初始值，显式指定 place 类型为 string[]
interface TableRow {
  sampleNo: string
  materialName: string
  model: string
  batch: string
  manufacturer: string
  physicalState: string
  color: string
  place: string[]
  post: string[]
  amount: string
  unit: string
  unitAuto?: boolean
  temperature: string
}

const form = ref<{ [key: string]: any; table: TableRow[] }>({
  taskNumber: '',
  sampleDate: new Date().toISOString().slice(0, 10),
  company: '',
  address: '',
  basis:
    props.testItem === '挥发性有机组分定性分析'
      ? '《化学品中挥发性有机组分定性分析和峰面积百分比测定顶空气相色谱-质谱法》GDOHTQC 001—2020'
      : props.testItem === '游离二氧化硅含量测定'
        ? '《工作场所空气中粉尘测定第4部分：游离二氧化硅含量》GBZ/T 192.4-2007'
        : '',
  type: '定期检测',
  item: props.testItem,
  table: []
})

const placeOptions = ref<string[]>([])
const postOptions = ref<string[]>([])
const name = ref()

// 获取取样场所选项
const getPlaceOptions = async () => {
  try {
    // 如果已经有选项了，就不再获取
    if (placeOptions.value.length > 0) {
      return
    }

    const { projectId } = route.query
    if (!projectId) {
      ElMessage.warning('项目ID不能为空')
      return
    }
    // 处理返回的数据，将斜杠替换为空格
    placeOptions.value = await ProjectApi.getWorkShopPositionNameTestItem(Number(projectId),name.value)
    console.log('获取取样场所选项:', JSON.stringify(placeOptions.value))

    // 如果没有数据，提醒用户
    if (placeOptions.value.length === 0) {
      ElMessage.warning('现场调查中原辅料中主要成分没有二氧化硅，请先完善现场调查数据')
    }
  } catch (error) {
    console.error('获取取样场所选项失败:', error)
    ElMessage.error('获取取样场所选项失败')
  }
}

// 获取代表/使用岗位选项
const getPostOptions = async () => {
  try {
    if (postOptions.value.length > 0) return
    const { projectId } = route.query
    if (!projectId) {
      ElMessage.warning('项目ID不能为空')
      return
    }
    postOptions.value = await ProjectApi.getWorkShopPositionName(Number(projectId),1)
    console.log('获取代表/使用岗位选项:', JSON.stringify(postOptions.value))
  } catch (error) {
    console.error('获取代表/使用岗位选项失败:', error)
    ElMessage.error('获取代表/使用岗位选项失败')
  }
}


// 处理下拉框显示状态变化
const handleVisibleChange = (visible: boolean) => {
  console.log('下拉框显示状态变化:', {
    visible: visible
  })
  if (visible && placeOptions.value.length === 0) {
    getPlaceOptions()
  }
}

// 代表/使用岗位 下拉显示时加载
const handlePostVisibleChange = (visible: boolean) => {
  if (visible && postOptions.value.length === 0) {
    getPostOptions()
  }
}

// 联动逻辑已移除 - 检测项目和采样依据不再联动，用户可以独立选择

const addRow = async () => {
  const sampleNo = await getSampleNo()
  console.log('获取样品编号:', sampleNo)
  // 确保取样场所选项已加载，用于默认选中
  if (placeOptions.value.length === 0) {
    await getPlaceOptions()
  }
 const ingredient=name.value==='二氧化硅'?'二氧化硅':'见定性结果'
  form.value.table.push({
    sampleNo: sampleNo,
    materialName: '',
    model: '—',
    batch: '—',
    manufacturer: '—',
    physicalState: '',
    color: '',
    place: [],
    // 默认选中"取样场所、岗位、地点"下拉中的所有选项
    post: [...placeOptions.value],
    amount: '',
    ingredient: ingredient,
    unit: 'g',
    unitAuto: true,
    temperature: ''
  })
}
const removeRow = (index: number) => {
  form.value.table.splice(index, 1)
}

const getSampleNo = async () => {
  const projectId = route.query.projectId as string
  return await ProjectApi.getSampleNo(Number(projectId))
}

const resetSampleNo = async () => {
  for (const item of form.value.table) {
    item.sampleNo = await getSampleNo()
  }
}
// 监听表单数据变化
watch(
  form,
  (newVal) => {
    emit('change', newVal)
  },
  { deep: true }
)

const handleUnitChange = (row: TableRow) => {
  row.unitAuto = false
}

const handlePhysicalStateChange = (row: TableRow) => {
  updateUnit(row)
}

const isLiquid = (state: string | undefined): boolean => {
  if (!state) return false
  const normalized = String(state).trim()
  // 支持“液体”“液态”及包含“液”字
  return /液/.test(normalized)
}

const updateUnit = (row: TableRow) => {
  if (row.unitAuto === undefined) row.unitAuto = true
  if (row.unit === undefined) row.unit = 'g'
  if (row.unitAuto !== false) {
    row.unit = isLiquid(row.physicalState) ? 'ml' : 'g'
  }
}

// 统一深度监听：初始化与任意变化时同步单位
watch(
  () => form.value.table,
  (rows) => {
    if (!Array.isArray(rows)) return
    for (const row of rows as any[]) {
      updateUnit(row as TableRow)
    }
  },
  { immediate: true, deep: true }
)

// 监听 testItem 的变化，自动设置检测项目
watch(
  () => props.testItem,
  (newVal) => {
    if (newVal) {
      form.value.item = newVal
      name.value = newVal==='挥发性有机组分定性分析'?'定性':'二氧化硅'
    }
  },
  { immediate: true }
)

// 监听检测项目变化，自动选中对应的采样依据
watch(
  () => form.value.item,
  (newVal) => {
    console.log(
      '检测项目变化，自动选中采样依据:',
      JSON.stringify({
        newItem: newVal,
        currentBasis: form.value.basis
      })
    )

    if (newVal === '挥发性有机组分定性分析') {
      form.value.basis =
        '《化学品中挥发性有机组分定性分析和峰面积百分比测定顶空气相色谱-质谱法》GDOHTQC 001—2020'
    } else if (newVal === '游离二氧化硅含量测定') {
      form.value.basis = '《工作场所空气中粉尘测定第4部分：游离二氧化硅含量》GBZ/T 192.4-2007'
    }
  }
)

// 暴露数据给父组件
defineExpose({
  form,
  addRow,
  resetSampleNo
})
</script>

<style lang="scss" scoped>
.chem-title {
  font-size: 26px;
  font-weight: 600;
  color: #222;
  flex-grow: 1;
  text-align: center;
}

.chem-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 0 0 24px 0;
  padding-bottom: 12px;
  border-bottom: 1px solid #e5e6eb;
}

.chem-form {
  background: none;
  box-shadow: none;
  border-radius: 0;
  margin-bottom: 0;

  :deep(.el-input__wrapper),
  :deep(.el-date-editor) {
    border-radius: 0 !important;
    box-shadow: none !important;
    background: #fff !important;
    border: 1px solid #e5e6eb;
  }

  :deep(.el-input__inner) {
    border-radius: 0 !important;
    box-shadow: none !important;
    background: #fff !important;
  }
}

.chem-btns {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
  align-items: center;
  margin-top: 0;
}

.chem-table {
  margin-top: 18px;
  --el-table-border-radius: 0 !important;
  --el-table-header-bg-color: #f7f8fa;
  --el-table-border-color: #e5e6eb;
  box-shadow: none !important;
  border-radius: 0 !important;

  :deep(.el-table__header th) {
    background: #f7f8fa !important;
    font-weight: 600;
    font-size: 14px;
    border-radius: 0 !important;
    padding: 8px 0 !important;

    .cell {
      padding-left: 0px !important;
      padding-right: 0px !important;
    }
  }

  :deep(.el-table__body td) {
    border-radius: 0 !important;
    background: #fff !important;
    font-size: 14px;
    padding: 0 !important;
  }

  :deep(.el-input__wrapper) {
    border-radius: 0 !important;
    box-shadow: none !important;
    background: #fff !important;
  }

  // 针对下拉选择框的所有相关元素去掉边框
  :deep(.el-select__wrapper) {
    border: none !important;
    box-shadow: none !important;
  }
}
</style>
